// STOPPED 操作相关的类型定义和处理逻辑

import { generateId } from "./utils";

// STOPPED 操作类型常量 - 来自后端工作流的人工干预请求
export const OPERATION_TYPES = {
  TRAVEL_GUIDE_CONFIRMATION: "__TRAVEL_GUIDE_CONFIRMATION__",
  FLIGHT_SELECTION: "__FLIGHT_SELECTION__",
  HOTEL_SELECTION: "__HOTEL_SELECTION__",
  ATTRACTION_RECOMMENDATION: "__ATTRACTION_RECOMMENDATION__",
} as const;

// 节点标签常量
export const NODE_LABELS = {
  TRAVEL_GUIDE_CONFIRMATION: "Q-人工操作-是否需要攻略",
  FLIGHT_SELECTION: "人工操作-航班自选",
  // 后续可以添加更多
  HOTEL_SELECTION: "人工操作-酒店选择",
  ATTRACTION_RECOMMENDATION: "人工操作-景点推荐",
} as const;

// 基础的 STOPPED 操作消息格式
export interface BaseOperationMessage {
  type: string;
  data: Record<string, any>;
}

// 人工输入操作（STOPPED 操作）
export interface HumanInputMessage extends BaseOperationMessage {
  id: string;
  answerId: string; // 关联的回答 ID
  messageItemId: string; // 关联的消息项 ID
  type: typeof OPERATION_TYPES.TRAVEL_GUIDE_CONFIRMATION;
  AIQuestion: string;
  data: {
    action: "proceed" | "reject" | "cancel"; // 用户的选择
    nodeId: string;
    nodeLabel: string; // 添加 nodeLabel 用于判断具体操作类型
    feedback?: string;
  };
}

// 航班选择操作（STOPPED 操作）
export interface FlightSelectionMessage extends BaseOperationMessage {
  type: typeof OPERATION_TYPES.FLIGHT_SELECTION;
  data: {
    flightInfo: string;
    nodeId: string;
    nodeLabel: string;
  };
}

// 所有支持的 STOPPED 操作消息类型
export type OperationMessage = HumanInputMessage | FlightSelectionMessage;

// STOPPED 节点的标签类型
export type StoppedNodeLabel =
  | typeof NODE_LABELS.TRAVEL_GUIDE_CONFIRMATION
  | typeof NODE_LABELS.FLIGHT_SELECTION;
// 后续可以添加更多类型

// STOPPED 操作处理器的配置
export interface StoppedOperationConfig {
  nodeLabel: StoppedNodeLabel;
  requiresData: boolean; // 是否需要有效数据才能显示
  modalType: "human-input" | "flight-selection"; // 弹窗类型
  dataValidator?: (data: any) => boolean; // 数据验证函数
  dataExtractor?: (eventData: any) => any; // 数据提取函数
  actionHandler?: (actionData: any) => any; // action 事件处理函数
}

// 支持的 STOPPED 操作配置
export const STOPPED_OPERATIONS: Record<
  StoppedNodeLabel,
  StoppedOperationConfig
> = {
  [NODE_LABELS.TRAVEL_GUIDE_CONFIRMATION]: {
    nodeLabel: NODE_LABELS.TRAVEL_GUIDE_CONFIRMATION,
    requiresData: false,
    modalType: "human-input",
    actionHandler: (actionData: any) => {
      // 处理攻略确认的 action 事件
      return {
        nodeId: actionData.data.nodeId,
        nodeLabel: actionData.data.nodeLabel,
        actionId: actionData.id,
        mapping: actionData.mapping,
        elements: actionData.elements,
      };
    },
  },
  [NODE_LABELS.FLIGHT_SELECTION]: {
    nodeLabel: NODE_LABELS.FLIGHT_SELECTION,
    requiresData: true,
    modalType: "flight-selection",
    dataValidator: (data: any) => {
      if (!data) {
        return false;
      }

      // 首先尝试从 action 事件数据结构中提取航班信息
      let flightData = null;

      // 检查是否是 action 事件的数据结构
      if (data.input && data.input.messages) {
        const userInfoMessage = data.input.messages.find(
          (msg: any) => msg.name === "用户信息提取",
        );
        if (userInfoMessage && userInfoMessage.content) {
          try {
            flightData = JSON.parse(userInfoMessage.content);
          } catch (e) {
            return false;
          }
        }
      } else {
        // 备用：尝试直接解析数据
        try {
          if (typeof data === "string") {
            const idx = data.indexOf("}");
            if (idx !== -1) {
              data = data.slice(0, idx + 1);
            }
            flightData = JSON.parse(data);
          } else {
            flightData = data;
          }
        } catch (e) {
          return false;
        }
      }

      if (!flightData) {
        return false;
      }

      // 检查必要的航班信息
      const departure = flightData["出发地"] || flightData.departure;
      const destination = flightData["目的地"] || flightData.destination;
      const departDate = flightData["出发时间"] || flightData.departDate;
      const returnDate = flightData["返回时间"] || flightData.returnDate;

      const isValid = !!(departure && destination && departDate && returnDate);

      return isValid;
    },
    dataExtractor: (eventData: any) => {
      // 从 action 事件中提取航班数据
      if (
        eventData.data &&
        eventData.data.input &&
        eventData.data.input.messages
      ) {
        const userInfoMessage = eventData.data.input.messages.find(
          (msg: any) => msg.name === "用户信息提取",
        );
        if (userInfoMessage && userInfoMessage.content) {
          return userInfoMessage.content;
        }
      }
      return null;
    },
  },
};

// 创建 STOPPED 操作消息的工厂函数

// 创建人工输入消息（STOPPED 操作）
export function createHumanInputMessage(
  action: "proceed" | "reject",
  nodeId: string,
  nodeLabel: string,
  answerId: string,
  messageItemId: string,
  feedback?: string,
): HumanInputMessage {
  return {
    id: generateId("humanInput"),
    answerId,
    messageItemId,
    type: OPERATION_TYPES.TRAVEL_GUIDE_CONFIRMATION,
    AIQuestion: "",
    data: {
      action,
      nodeId,
      nodeLabel,
      feedback,
    },
  };
}

// 创建航班选择消息（STOPPED 操作）
export function createFlightSelectionMessage(
  flightInfo: string,
  nodeId: string,
  nodeLabel: string,
): FlightSelectionMessage {
  return {
    type: OPERATION_TYPES.FLIGHT_SELECTION,
    data: {
      flightInfo,
      nodeId,
      nodeLabel,
    },
  };
}

// 解析操作消息
export function parseOperationMessage(
  content: string,
): OperationMessage | null {
  try {
    if (content.startsWith("{")) {
      const parsed = JSON.parse(content);
      if (
        parsed.type &&
        parsed.data &&
        Object.values(OPERATION_TYPES).includes(parsed.type)
      ) {
        return parsed as OperationMessage;
      }
    }
  } catch (e) {
    console.error("Failed to parse operation message:", e);
  }
  return null;
}

// 验证操作消息格式
export function isValidOperationMessage(
  message: any,
): message is OperationMessage {
  return (
    message &&
    typeof message.type === "string" &&
    message.data &&
    typeof message.data === "object"
  );
}

// 为 STOPPED 操作生成用户友好的显示文本
export function formatOperationMessageForDisplay(
  message: OperationMessage,
): string {
  switch (message.type) {
    case OPERATION_TYPES.TRAVEL_GUIDE_CONFIRMATION:
      const humanMsg = message as HumanInputMessage;
      return humanMsg.data.action === "proceed"
        ? "✅ 确认需要攻略"
        : "❌ 不需要攻略";

    case OPERATION_TYPES.FLIGHT_SELECTION:
      const flightMsg = message as FlightSelectionMessage;
      // 尝试解析航班信息，只显示核心信息
      try {
        const flightData = JSON.parse(flightMsg.data.flightInfo);
        const departure =
          flightData["出发地"] || flightData.departure || "未知";
        const destination =
          flightData["目的地"] || flightData.destination || "未知";
        const departDate =
          flightData["出发时间"] || flightData.departDate || "未知";

        return `✈️ 选择航班：${departure} → ${destination}，出发时间：${departDate}`;
      } catch {
        // 如果解析失败，返回简化的信息
        return "✈️ 确认航班选择";
      }

    default:
      return "确认操作";
  }
}
